﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using FileDownload;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.Win32;

namespace Unplash_Moka
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            GetConfig();
            GetConfig1();
            Main_timer_Refresh.Interval = RefreshMinuts * 60 * 1000;
            Main_timer_Refresh.Enabled = true;
            notifyIcon1.Visible = true;
            开机启动ToolStripMenuItem.Checked = AutoStart != 0;
            WindowState = FormWindowState.Minimized;
        }

        #region 定义
        private HttpDownload DownlaodMethod;
        private static string Url = "https://source.unsplash.com/random/2560x1440";
        private static string DownloadPath = @"D:\WallPapers\temp.jpg";
        private static string WallPaperPath = @"D:\WallPapers\temp.bmp";
        private int RefreshMinuts = 30;
        private int AutoStart = 0;
        private static string ConfigFolderPath = Application.StartupPath;
        private static string ConfigFilePath = ConfigFolderPath + @"\Config.ini";
        private static string Config1FilePath = ConfigFolderPath + @"\Config1.ini";
        #endregion

        #region 方法
        /// <summary>
        /// 下载背景图片 from unplash
        /// </summary>
        private void DownloadUnplash()
        {
            DownlaodMethod = new HttpDownload();
            if (!isFileInUse(DownloadPath))
            {
                DownlaodMethod.Download(Url, DownloadPath);
            }
        }

        private static bool isFileInUse(string filename)
        {
            bool isUse = true;
            FileStream fs = null;
            try
            {
                fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.None);
                isUse = false;
            }
            catch
            {
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }
            return isUse;
        }

        [DllImport("user32.dll", EntryPoint = "SystemParametersInfo")]
        public static extern int SystemParametersInfo(
            int uAction,
            int uParam,
            string lpvParam,
            int fuWinIni);

        private bool UpdateWallPaper()
        {
            try
            {
                Image image = Image.FromFile(DownloadPath);
                image.Save(WallPaperPath, System.Drawing.Imaging.ImageFormat.Bmp);
                SystemParametersInfo(20, 0, WallPaperPath, 0x2);
                image.Dispose();
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }

        private void Main()
        {
            DownloadUnplash();
            UpdateWallPaper();
            File.Delete(DownloadPath);
        }
        #endregion

        private void Main_btn_Apply_Click(object sender, EventArgs e)
        {
            RefreshMinuts = int.Parse(Main_txb_Minuts.Text);
            Main_timer_Refresh.Interval = RefreshMinuts * 60 * 1000;
            SetConfig(RefreshMinuts);

        }

        private void CheckConfig()
        {
            if (!Directory.Exists(ConfigFolderPath))
            {
                Directory.CreateDirectory(ConfigFolderPath);
            }

            if (!File.Exists(ConfigFilePath))
            {
                FileStream nfs = new FileStream(ConfigFilePath, FileMode.Create, FileAccess.Write);
                StreamWriter nsw = new StreamWriter(nfs);
                nsw.WriteLine("30");
                nsw.Close();
                nfs.Close();
            }
        }

        private void CheckConfig1()
        {
            if (!Directory.Exists(ConfigFolderPath))
            {
                Directory.CreateDirectory(ConfigFolderPath);
            }

            if (!File.Exists(Config1FilePath))
            {
                FileStream nfs = new FileStream(Config1FilePath, FileMode.Create, FileAccess.Write);
                StreamWriter nsw = new StreamWriter(nfs);
                nsw.WriteLine("0");
                nsw.Close();
                nfs.Close();
            }
        }

        private void GetConfig()
        {
            CheckConfig();

            FileStream fs = new FileStream(ConfigFilePath,FileMode.Open,FileAccess.Read);
            StreamReader sr = new StreamReader(fs);
            string tmpstr = sr.ReadToEnd();
            RefreshMinuts = int.Parse(tmpstr);
            sr.Close();
            fs.Close();
        }

        private void GetConfig1()
        {
            CheckConfig1();

            FileStream fs = new FileStream(Config1FilePath, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs);
            string tmpstr = sr.ReadToEnd();
            AutoStart = int.Parse(tmpstr);
            sr.Close();
            fs.Close();
        }

        private void SetConfig(int minuts)
        {
            CheckConfig();

            FileStream fs = new FileStream(ConfigFilePath,FileMode.Open,FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine(minuts.ToString());
            sw.Close();
            fs.Close();
        }

        private void SetConfig1(int autostart)
        {
            CheckConfig();

            FileStream fs = new FileStream(Config1FilePath, FileMode.Open, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);
            sw.Write(autostart.ToString());
            sw.Close();
            fs.Close();
        }

        private void Main_timer_Refresh_Tick(object sender, EventArgs e)
        {
            Main();
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                WindowState = FormWindowState.Normal;
                this.Activate();
                this.ShowInTaskbar = true;
                notifyIcon1.Visible = true;
            }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.Dispose();
            this.Close();
        }

        private void MainForm_SizeChanged(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                this.ShowInTaskbar = false;
                notifyIcon1.Visible = true;
            }
        }

        private void 显示ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            WindowState = FormWindowState.Normal;
            this.Activate();
            notifyIcon1.Visible = true;
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Dispose();
            this.Close();
        }

        private void 开机启动ToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
        {
            
            if (开机启动ToolStripMenuItem.Checked)
            {
                SetConfig1(1);
                string path = Application.ExecutablePath;
                RegistryKey rk = Registry.LocalMachine;
                RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
                rk2.SetValue("JcShutdown", path);
                rk2.Close();
                rk.Close();
            }
            else
            {
                SetConfig1(0);
                string path = Application.ExecutablePath;
                RegistryKey rk = Registry.LocalMachine;
                RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
                rk2.DeleteValue("JcShutdown", false);
                rk2.Close();
                rk.Close();
            }
        }

        private void Main_btn_RefreshNow_Click(object sender, EventArgs e)
        {
            Main();
        }

        private void 刷新壁纸ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Main();
        }
    }
}
